﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Drawing;
using Barbar.MapReport.Common.Drawing;
using System.Globalization;

namespace Barbar.MapReport.HtmlRender.Operations.Legends {
  internal class LegendHtmlRender {
    private LegendRangeList m_Legend;
    private ILegendDescription m_Description;

    public LegendHtmlRender(LegendRangeList legend, ILegendDescription description) {
      if (legend == null)
        throw new ArgumentNullException("legend");
      if (description == null)
        throw new ArgumentNullException("description");
      m_Legend = legend;
      m_Description = description;
    }

    private HtmlTableCell CreateCellWithColorRect(Color color) {
      HtmlTableCell cell = new HtmlTableCell();
      HtmlGenericControl div = new HtmlGenericControl("div");
      div.Style.Add(HtmlTextWriterStyle.Width, "20px");
      div.Style.Add(HtmlTextWriterStyle.Height, "15px");
      div.Style.Add(HtmlTextWriterStyle.BackgroundColor, ColorTranslator.ToHtml(color));
      div.Style.Add(HtmlTextWriterStyle.BorderColor, "#000000");
      div.Style.Add(HtmlTextWriterStyle.BorderStyle, "solid");
      div.Style.Add(HtmlTextWriterStyle.BorderWidth, "1px");
      cell.Controls.Add(div);
      cell.Width = "25px";
      return cell;
    }

    internal HtmlControl CreateLegendMarkup() {
      HtmlControl result = new HtmlGenericControl("div");

      if (!String.IsNullOrEmpty(m_Description.Title)) {
        HtmlGenericControl title = new HtmlGenericControl("span");
        title.InnerText = m_Description.Title;
        result.Controls.Add(title);
      }

      HtmlTable table = new HtmlTable();
      result.Controls.Add(table);

      NumberFormatInfo nfi = new NumberFormatInfo();
      nfi.NumberGroupSeparator = " ";
      nfi.NumberDecimalDigits = 0;

      bool isFirst = true;
      foreach (LegendRange entry in m_Legend) {
        HtmlTableRow row = new HtmlTableRow();
        table.Rows.Add(row);
        row.Cells.Add(CreateCellWithColorRect(entry.Color));

        HtmlTableCell cellLeft = new HtmlTableCell();
        if (entry.From == entry.To && isFirst && entry.From >= 0)
          cellLeft.InnerText = String.Format(nfi, "{0:n}", 0m);
        else
          cellLeft.InnerText = String.Format(nfi, "{0:n}", entry.From);
        cellLeft.Align = "right";
        row.Cells.Add(cellLeft);

        HtmlTableCell cellMiddle = new HtmlTableCell();
        cellMiddle.InnerText = "-";
        row.Cells.Add(cellMiddle);

        HtmlTableCell cellRight = new HtmlTableCell();
        cellRight.InnerText = String.Format(nfi, "{0:n} {1}", entry.To, m_Description.UnitName == null ? String.Empty : m_Description.UnitName);
        cellRight.Align = "right";
        row.Cells.Add(cellRight);

        isFirst = false;
      }
      return result;
    }
  }
}
